import {
  $digest,
  $init
} from '../../lib/page.data'
import {
  $request,
  Session
} from '../../lib/page.auth'

const {
  regeneratorRuntime
} = global;
let recorder = wx.getRecorderManager();
//获取应用实例
let api = require('../../utils/api.js');
let http = require('../../utils/http.js');
let util = require('../../utils/util.js');

// pages/minePersonal/minePersonal.js
var timer = null;
var time = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    submitEnable: false,
    sex: ['保密', '男', '女'],
    date: '2018-09-20',
    
    label: [{
        name: '0',
        value: '大叔',
        checked: false,
      },
      {
        name: '1',
        value: '正太',
        checked: true,
      },
      {
        name: '2',
        value: '青年',
        checked: false,
      },
      {
        name: '3',
        value: '逗逼',
        checked: false,
      },
      {
        name: '4',
        value: '高冷',
        checked: false,
      },
      {
        name: '5',
        value: '大神',
        checked: true,
      },
      {
        name: '6',
        value: '小奶狗',
        checked: true,
      },
      {
        name: '7',
        value: '话痨',
        checked: false,
      },
      {
        name: '8',
        value: '话痨2',
        checked: false,
      },
    ],
    personalPic: [], //封面照片
    figureImg: [], //形象照片  最多6张

    torecord: false,
    record: false,
    timeLength: 0,
    recordTime: 0,
    iconShow: false,
    cover_id: null,
    checkProcotol: 0,
    //样例图片
    sampleImg: [
      'https://sy.tutu-yun.com/upload/wxapp/face.jpg',
      'https://sy.tutu-yun.com/upload/wxapp/black.jpg'
    ],
    IdCardFId: '',
    IdCardZId: '',
    IdCardFPic:'',
    IdCardZPic:''
    //recordFile
  },
  // 查看样例
  previewImage: function(e) {
    var that = this,
      //获取当前图片的下表
      imgId = e.currentTarget.dataset.id,
      //数据源
      pictures = this.data.sampleImg;
    console.log(pictures[imgId])
    wx.previewImage({
      //当前显示下表
      current: pictures[imgId],
      //数据源
      urls: pictures
    })
  },
  playAudio(e) {
    this.innerAudioContext = wx.createInnerAudioContext();
    this.innerAudioContext.onError((res) => {
      // 播放音频失败的回调
      console.log('############播放音频失败################');
      console.log(res);
    });
    this.innerAudioContext.src = this.data.recordFile; // 这里可以是录音的临时路径
    this.innerAudioContext.play();
  },

  recordTap: function() {
    this.setData({
      torecord: true
    });
    // this.data.torecord = true
  },

  recordStart: function(e) {
    var that = this;
    that.setData({
      record: true,
      timeLength: 0,
    });

    recorder.onStop(function(res) { //监听录音结束
      console.log("##################");
      console.log(res.tempFilePath);
      that.data.recordFile = res.tempFilePath;
    });

    recorder.onError(function(res) {
      // 录音失败的回调处理
      console.log('#######录音失败############');
      console.log(res);
    });

    recorder.start({
      duration: 60000, //录音时长：一分钟
      format: 'mp3', //音频格式 ：mp3格式
    });

    var timeLength = that.data.timeLength;
    timer = setInterval(function() {
      timeLength++;
      if (timeLength == 60) {
        clearInterval(timer);
      }
      that.setData({
        timeLength: timeLength
      })
    }, 1000)
  },

  //停止录音
  stopRecord: function(e) {
    var that = this;
    clearInterval(timer);
    recorder.stop(); //停止录音
    that.setData({
      iconShow: true
    });
  },

  recordEnd: function(e) {
    console.log(2, e);
    clearInterval(timer);
    var that = this;
    wx.stopRecord(); //结束录音
    that.setData({
      iconShow: true
    });
  },

  backTap: function() {
    this.setData({
      torecord: false,
      record: false,
      iconShow: false,
      timeLength: 0
    });
  },

  confirmTap: function() {
    var that = this;
    var token = wx.getStorageSync('token');
    var timeLength = this.data.timeLength;
    if (timeLength < 5) {
      wx.showToast({
        title: '录音不能短于5秒钟',
        icon: 'none',
        image: '',
        duration: 1000,
        mask: true,
        success: function(res) {},
        fail: function(res) {},
        complete: function(res) {},
      })
    } else {
      //上传录音文件
      console.log(this.data.recordFile, '=========')
      wx.uploadFile({
        url: api.audio_upload, //仅为示例，非真实的接口地址
        filePath: that.data.recordFile,
        name: 'file',
        formData: {
          'module': 'wx_audio',
          'token': token
        },
        success(res) {
          const data = JSON.parse(res.data);
          if (data.code == 1) {
            let audio_data = data.data;
            that.data.audio_id = audio_data.id;
            console.log("audio_path:" + audio_data.path);
            that.setData({
              src: audio_data.path
            });
          }
        }
      })
      this.setData({
        torecord: false,
        record: false,
        iconShow: false,
        recordTime: this.data.timeLength,
        timeLength: 0
      });
    }
  },
  realName: function(e) {
    var user_ = this.data.user;
    user_.realName = e.detail.value;
  },
  high: function(e) {
    var user_ = this.data.user;
    user_.high = e.detail.value;
  },
  weight: function(e) {
    var user_ = this.data.user;
    user_.weight = e.detail.value;
  },

  sexChange: function(e) {
    var user_ = this.data.user;
    user_.gender = e.detail.value;
    this.setData({
      user: user_
    })
  },
  dateChange: function(e) {
    console.log(this.data.user);
    var user_ = this.data.user;
    user_.birth = e.detail.value;
    console.log(user_.birth)
    console.log(user_)
    this.setData({
      user: user_
    })
  },
  //上传身份证正面
  IdCardZImg: function() {
    var that = this;
    var token = wx.getStorageSync('token');
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      success: function(res) {
        const tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        wx.uploadFile({
          url: api.image_upload,
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            'module': 'wx_images',
            'token': token,
            'type': 1
          },
          success(res) {
            const data = JSON.parse(res.data);
            console.log(res)
            if (data.code == 1) {
              let cover_data = data.data;
              that.data.IdCardZId = cover_data.id
            }
            console.log(that.data.cover_id, '图片ID')
          }
        });
        that.setData({
          IdCardZPic: res.tempFilePaths
        })
      },
    })
  },
  //编辑身份证正面
  editIdCardZ() {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      success: function(res) {
        that.setData({
          IdCardZPic: res.tempFilePaths
        });
        that.uploadIdCardZImage(res.tempFilePaths[0]);
      },
    })
  },
  //删除身份证正面
  deleteIdCardZ: function(e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除身份证正面照吗?',
      success: function(res) {
        if (res.confirm) {
          that.setData({
            IdCardZPic: [],
            cover_id: null
          });
        }
      }
    })
  },
  //上传身份证反面
  IdCardFImg: function() {
    var that = this;
    var token = wx.getStorageSync('token');
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      success: function(res) {
        const tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        wx.uploadFile({
          url: api.image_upload,
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            'module': 'wx_images',
            'token': token,
            'type': 2
          },
          success(res) {
            const data = JSON.parse(res.data);
            console.log(res)
            if (data.code == 1) {
              let cover_data = data.data;
              that.data.IdCardFId = cover_data.id
            }
            console.log(that.data.cover_id, '图片ID')
          }
        });
        that.setData({
          IdCardFPic: res.tempFilePaths
        })
      },
    })
  },
  //编辑身份证正面
  editIdCardF() {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      success: function(res) {
        that.setData({
          IdCardFPic: res.tempFilePaths
        });
        that.uploadIdCardFImage(res.tempFilePaths[0]);
      },
    })
  },
  //删除身份证正面
  deleteIdCardF: function(e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除身份证反面照吗?',
      success: function(res) {
        if (res.confirm) {
          that.setData({
            IdCardFPic: [],
            cover_id: null
          });
        }
      }
    })
  },
  //上传封面
  personalImg: function() {
    var that = this;
    var token = wx.getStorageSync('token');
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      success: function(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: api.image_upload, //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            'module': 'wx_images',
            'token': token
          },
          success(res) {
            const data = JSON.parse(res.data);
            if (data.code == 1) {
              let cover_data = data.data;
              that.data.cover_id = cover_data.id
            }
            console.log(that.data.cover_id, '图片ID')
          }
        });
        that.setData({
          personalPic: res.tempFilePaths
        })
      },
    })
  },
// 删除封面
  deleteTap: function(e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除封面照片吗?',
      success: function(res) {
        if (res.confirm) {
          that.setData({
            personalPic: [],
            cover_id: null
          });
        }
      }
    })
  },

  //编辑封面图
  editPersonal() {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      success: function(res) {
        that.setData({
          personalPic: res.tempFilePaths
        });
        that.uploadImage(res.tempFilePaths[0]);
      },
    })
  },
  //形象照多图上传
  uploadMore: function(figureImg) {
    var i = figureImg.i ? figureImg.i : 0;
    var that = this;
    var token = wx.getStorageSync('token');
    wx.uploadFile({
      url: api.image_upload,
      filePath: figureImg[i],
      name: 'file',
      formData: {
        'module': 'wx_images',
        'token': token
      },
      success(res) {
        const data = JSON.parse(res.data)
        if (data.code == 1) {
          console.log(res)

          // let image_data = data.data;
          // let img_data = {id: parseInt(image_data.id), path: image_data.path};
          // var imageIds = []
          that.data.image_ids.push(parseInt(data.data.id))
          // that.setData({ image_ids: data.data.id})
          console.log(that.data.image_ids)
        }
      },
      complete(res) {
        i++;
        if (i == figureImg.length) {
          console.log('完')
        } else {
          console.log(res)
          figureImg.i = i;
          that.uploadMore(figureImg)
        }
      }
    });
  },
  //上传形象照
  figureTap: function() {
    var figureImg = this.data.figureImg;
    var that = this;


    wx.chooseImage({
      count: 6 - this.data.figureImg.length,
      sizeType: ['original', 'compressed'],
      success: function(res) {
        console.log(res.tempFilePaths);
        for (var i = 0; i < res.tempFilePaths.length; i++) {
          if (figureImg.length < 6) {
            figureImg.push(res.tempFilePaths[i])
          }
        }
        console.log(figureImg);
        that.setData({
          figureImg: figureImg
        })
        that.uploadMore(figureImg)
      },
    })


  },
  // 删除形象照
  deleteFigure: function(e) {
    var id = e.target.dataset.id;
    var figureImg = this.data.figureImg;
    var image_ids = this.data.image_ids;
    // var newArr = figureImg.filter(function (obj) {
    //     return id !== obj.id;
    // });
    figureImg.splice(id, 1)
    image_ids.splice(id, 1)
    console.log(figureImg)
    console.log(image_ids)
    this.setData({
      figureImg: figureImg,
      image_ids: image_ids
    })
  },
  // 修改形象照
  editFigure: function(e) {
    var id = e.target.dataset.id;
    var item = "figureImg[" + id + "]";
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      success: function(res) {
        that.setData({
          [item]: res.tempFilePaths,
          
        });
        that.uploadfigureImg(res.tempFilePaths[0], id);
      },
    })
  },
  //上传形象照
  uploadfigureImg(filepath, id) {
    var that = this;
    var token = wx.getStorageSync('token');
    wx.uploadFile({
      url: api.image_upload,
      filePath: filepath,
      name: 'file',
      formData: {
        'module': 'wx_images',
        'token': token
      },
      success(res) {
        const data = JSON.parse(res.data);
        console.log(res.data)
        if (data.code == 1) {
          var image_data = data.data; 
          image_ids: that.data.image_ids.splice(id, 1, image_data.id);
        }
      }
    });
  },
  // 选择标签
  checkChange: function(e) {
    var that = this;
    var items = this.data.label;
    var checkArr = e.detail.value;
    this.data.labelid = checkArr
    console.log(this.data.labelid)

    for (var i = 0; i < items.length; i++) {
      if (checkArr.indexOf(items[i].id + "") != -1) {
        items[i].checked = true;
      } else {
        items[i].checked = false;
      }
    }
    this.setData({
      label: items
    });
  },

  //上传封面图
  uploadImage(filepath) {
    var that = this;
    var token = wx.getStorageSync('token');
    wx.uploadFile({
      url: api.image_upload,
      filePath: filepath,
      name: 'file',
      formData: {
        'module': 'wx_images',
        'token': token
      },
      success(res) {
        const data = JSON.parse(res.data);
        console.log(res)
        if (data.code == 1) {
          var image_data = data.data;
          that.data.cover_id = image_data.id;
        }
      }
    });
  },
  //上传身份证正面图
  uploadIdCardZImage(filepath) {
    var that = this;
    var token = wx.getStorageSync('token');
    wx.uploadFile({
      url: api.image_upload,
      filePath: filepath,
      name: 'file',
      formData: {
        'module': 'wx_images',
        'token': token,
        'type': 1
      },
      success(res) {

        const data = JSON.parse(res.data);
        console.log(res)
        if (data.code == 1) {
          let cover_data = data.data;
          that.data.IdCardZId = cover_data.id
        }
      }
    });
  },
  //上传身份证反面图
  uploadIdCardFImage(filepath) {
    var that = this;
    var token = wx.getStorageSync('token');
    wx.uploadFile({
      url: api.image_upload,
      filePath: filepath,
      name: 'file',
      formData: {
        'module': 'wx_images',
        'token': token,
        'type': 2
      },
      success(res) {

        const data = JSON.parse(res.data);
        console.log(res)
        if (data.code == 1) {
          let cover_data = data.data;
          that.data.IdCardFId = cover_data.id
        }
      }
    });
  },
  //提交表单
  async formSubmit(e) {
    console.log(e.detail.value)
    var token = wx.getStorageSync('token');

    let form_id = e.detail.formId;
    await util.getFormIds(form_id);
    console.log(this.data.checkProcotol);
    if (this.data.checkProcotol === 0) {
      wx.showModal({
        title: '提示',
        content: '请同意用户协议！',
        success: function(res) {
          console.log(res.confirm);
          // return;
        },
      })
      return;
    }
    if (e.detail.value.realName == ""){
      wx.showToast({
        title: '请输入真实姓名',
        icon: 'none'
      });
      return;
    }
    if (e.detail.value.high == "") {
      wx.showToast({
        title: '请输入身高',
        icon: 'none'
      });
      return;
    }
    if (e.detail.value.weight == "") {
      wx.showToast({
        title: '请输入体重',
        icon: 'none'
      });
      return;
    }
    if (this.data.IdCardFId == "" || this.data.IdCardFId == null) {
      wx.showToast({
        title: '请上传身份证反面',
        icon: 'none'
      });
      return;
    }
    if (this.data.IdCardZId == "" || this.data.IdCardZId == null) {
      wx.showToast({
        title: '请上传身份证正面',
        icon: 'none'
      });
      return;
    }
    if (this.data.cover_id == "" || this.data.cover_id == null) {
      wx.showToast({
        title: '请上传封面图',
        icon: 'none'
      });
      return;
    }
    let image_data = this.data.figureImg
    
    this.setData({
      submitEnable: true
    });

    let data = e.detail.value;
    console.log(data)
    data.form_id = form_id;
    data.cover_id = this.data.cover_id;
    data.images = this.data.image_ids;
    data.labels = this.data.labelid;
    data.token = token;
    data.audio_id = this.data.audio_id;
    data.IdCardF = this.data.IdCardFId;
    data.IdCardZ = this.data.IdCardZId;
    // data.realName = this.user.realName

    http.post(api.user_check_submit, data, function(res) {
      if (res.data.code == 0) {
        util.msg('提交失败！');
        return;
      }
    }, '数据提交中...');

    this.setData({
      submitEnable: false
    });

    wx.showModal({
      title: '提示',
      content: '提交完成，等待平台审核',
      success: function(res) {
        console.log(res.confirm);
        if (res.confirm) {
          var pages = getCurrentPages(); // 当前页面
          var beforePage = pages[pages.length - 2]; // 前一个页面
          wx.navigateBack({
            success: function() {
              beforePage.onLoad(); // 执行前一个页面的onLoad方法
            }
          });
        }
      },
    })

    // const res = $request({url: api.user_check_submit, data: data, method: 'POST'})
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    var that = this;
    var token = wx.getStorageSync('token');
    http.get(api.user_check, {
      token: token
    }, function(res) {
      console.log(res.data, '+++++++++')
      var user_data = res.data.data;
      if (res.data.code == 1) {
        that.setData({
          user: user_data,
          label: user_data.label,
          voicePath: user_data.audio,
          IdCardFId: user_data.IdCardF,
          IdCardZId:user_data.IdCardZ,
          recordFile: api.oss_domain + user_data.audio.path
        });
        if (user_data.IdCardF_img.length !== 0) {
          let IdCardFPic = [user_data.IdCardF_img];
          that.setData({
            IdCardFPic: IdCardFPic,
          })
        }
        if (user_data.IdCardZ_img.length !== 0) {
          let IdCardZPic = [user_data.IdCardZ_img];
          that.setData({
            IdCardZPic: IdCardZPic,
          })
        }
        if (user_data.cover.length !== 0) {
          let cover = [user_data.cover];
          that.setData({
            personalPic: cover,
            cover_id: user_data.cover_id
          })
        }
        if (user_data.images !== 0){
          let figureImg = [];
          let image_ids =[];
          for (var i = 0; i < user_data.images.length;i++){
            figureImg.push(user_data.images[i].path) 
            image_ids.push(user_data.images[i].id) 
          }
          that.setData({
            figureImg: figureImg,
            image_ids: image_ids
          })
        }
      } else {
        wx.showModal({
          title: "提示",
          content: res.data.info,
          showCancel: false
        });
      }
    }, "请求中...");

  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  showProtocol() {
    wx.navigateTo({
      url: '/pages/protocol/protocol?pid=4',
    })
  },

  checkProcotol(e) {
    let check;
    if (e.detail.value == '') {
      check = 0
    } else {
      check = 1
    }

    // console.log(e.detail.value);
    console.log(check);
    this.setData({
      checkProcotol: check
    });
  },
})